package com.mas.admin.biz.controller.admin.auth;

import cn.hutool.core.util.StrUtil;
import com.mas.admin.biz.controller.admin.auth.vo.AuthLoginReqVO;
import com.mas.admin.biz.controller.admin.auth.vo.AuthLoginRespVO;
import com.mas.admin.biz.service.auth.AdminAuthService;
import com.mas.admin.enums.logger.LoginLogTypeEnum;
import com.mas.framework.common.pojo.CommonResult;
import com.mas.framework.security.config.SecurityProperties;
import com.mas.framework.security.core.util.SecurityFrameworkUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import static com.mas.framework.common.pojo.CommonResult.success;

/**
 * @author godyao
 * @description 管理后台-认证
 * @date 2023年01月28日23:01
 */
@Api(tags = "管理后台-认证")
@RestController
@RequestMapping("/system/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AdminAuthService authService;

    private final SecurityProperties securityProperties;

    @PostMapping("/login")
    @PermitAll
    @ApiOperation("使用账号密码登录")
    public CommonResult<AuthLoginRespVO> login(@RequestBody @Valid AuthLoginReqVO reqVO) {
        return success(authService.login(reqVO));
    }

    @PostMapping("/logout")
    @PermitAll
    @ApiOperation("登出系统")
    public CommonResult<Boolean> logout(HttpServletRequest request) {
        final String token = SecurityFrameworkUtils.obtainAuthorization(request, securityProperties.getTokenHeader());
        if (StrUtil.isNotEmpty(token)) {
            authService.logout(token, LoginLogTypeEnum.LOGOUT_SELF.getType());
        }
        return success(true);
    }

    @PostMapping("/refreshToken")
    @PermitAll
    @ApiOperation("刷新令牌")
    @ApiImplicitParam(value = "刷新令牌", name = "refreshToken", required = true, dataTypeClass = String.class)
    public CommonResult<AuthLoginRespVO> refreshToken(String refreshToken) {
        return success(authService.refreshToken(refreshToken));
    }


}
